
#include "Outlet_Manager.h"
#include "ex_util.h"
#include "define.h"

COutlet_Manager::COutlet_Manager()
{
}

COutlet_Manager::~COutlet_Manager()
{
}

bool COutlet_Manager::init()
{
	bool bRet = false;

	do 
	{
		/*
		parent init call
		*/

		CCLayer::init();

		CreateOutlet();

		// success
		bRet = true;
	} while(0);

	return bRet;
}

void COutlet_Manager::CreateOutlet()
{
	memset(&m_nColorsCount, 0, sizeof(int)*E_OUTLET_MAX);

	for( int i=0; i<OUTLET_TOTAL_COUNT-4; i++)
	{
		int nColor = GenerateValidType();
		COutlet* pOutlet = COutlet::outletWithType(nColor);
		pOutlet->setAnchorPoint(ccp(0.5f, 0.5f));
		if( i < 5 )
		{
			pOutlet->setPosition( ccp( 48+(56*i), 470) );
			m_vOutletTop.push_back(pOutlet);
		}
		else if( i >= 5 && i < 10 )
		{
			pOutlet->setPosition( ccp( 48+(56*(i-5)), 58) );
			m_vOutletBottom.push_back(pOutlet);
		}
		else if( i >= 10 && i < 15 )
		{
			pOutlet->setPosition( ccp( 10, 150+(56*(i-10)) ) );
			m_vOutletLeft.push_back(pOutlet);
		}
		else if( i >= 15 && i < 20 )
		{
			pOutlet->setPosition( ccp( 310, 150+(56*(i-15)) ) );
			m_vOutletRight.push_back(pOutlet);
		}

		addChild(pOutlet);

		m_vOutlet.push_back(pOutlet);
	}
}

void COutlet_Manager::ShuffleOutlet()
{
	/*
		top - start point 48,10
		bottom - start point 48,422

		horizontal - start point 10,48
		horizontal - start point 310,48
	*/
	
	memset(&m_nColorsCount, 0, sizeof(int)*E_OUTLET_MAX);

	for( int i=0; i<m_vOutlet.size(); i++)
	{
		int nColor = GenerateValidType();
		m_vOutlet[i]->changeType(nColor);
	}
}

int COutlet_Manager::GenerateValidType()
{
	int nColor = 0;

	while(1)
	{
		float fRand = EX_UTIL::GetRand();
		nColor = (int)fRand%E_OUTLET_MAX;

		if( m_nColorsCount[nColor] < (OUTLET_TOTAL_COUNT/E_OUTLET_MAX)+1 )
		{
			m_nColorsCount[nColor]++;
			break;
		}
	}

	return nColor;
}

COutlet* COutlet_Manager::GetOutlet(int nIdx)
{
	if( nIdx <=0 || m_vOutlet.size() <= nIdx )
		return NULL;

	return m_vOutlet[nIdx];
}

int COutlet_Manager::GetOutletCount()
{
	return m_vOutlet.size();
}